var prefix = jsctx + "/enterprise/level/setting";

var enterpriseLevel = (function () {
    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
        load();
    };

    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };
    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listPageLevelSetting",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: true,
                singleSelect: false,
                pageList: [10, 20, 30],
                pageSize: 10,
                pageNumber: 1,
                sidePagination: "server",
                cache: false,
                height: h,
                paginationShowPageGo: true,
                rightFixedColumns: false,
                queryParams: function (params) {
                    return {
                        pageNo: (params.offset / params.limit) + 1,
                        pageSize: params.limit,
                        levelName: $("#levelName").val(),
                    };
                },
                columns: [
                    {
                        field: 'number',
                        title: '序号',
                        width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                    {field: 'levelName', title: '等级名称', align: 'center'},
                    {
                        field: 'levelLogo', title: '企业标识图标', align: 'center',
                        formatter: function (value, row, index) {
                            if (value != null && value != '') {
                                return "<img src=" + value + " width='50px' height='50px'>";
                            }
                        }
                    },
                    {field: 'rechargeAmount', title: '充值金额(元)', align: 'center'},
                    {
                        field: 'discountAmount', title: '消费折扣', align: 'center',
                        formatter: function (value, row, index) {
                            return (value*10) + '折';
                        }
                    },
                    // {field: 'creditAmountTarget', title: '授信额(元)', align: 'center'},
                    {field: 'createdTime', title: '创建时间', align: 'center'},
                    {
                        title: '操作',
                        field: 'orderId',
                        width: '200', align: 'center',
                        formatter: function (value, row, index) {
                            var a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" mce_href="#" title="编辑" onclick="enterpriseLevel.editEnterpriseLevel(\''
                                + row.enterpriseLevel + '\')">编辑</a> ';

                            var d = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" mce_href="#" title="删除" onclick="enterpriseLevel.deleteEnterpriseLevel(\''
                                + row.enterpriseLevel + '\')">删除</a> ';

                            return a + d;
                        }
                    }
                ], onLoadSuccess: function () {
                    initSwitch();
                }, onPageChange: function () {
                    initSwitch();
                }
            });
    };
    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                levelName: $('#levelName').val().trim(),
                offset: $('.active .page-link').text() || 1,
                limit: $(".page-size").text() || 10
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    function initSwitch() {
        $("[name='enterprise-status']").bootstrapSwitch({
            onText: "启用",      // 设置ON文本
            offText: "禁用",    // 设置OFF文本
            onColor: "primary",// 设置ON文本颜色(info/success/warning/danger/primary)
            offColor: "warning",  // 设置OFF文本颜色 (info/success/warning/danger/primary)
            size: "mini",    // 设置控件大小,从小到大  (mini/small/normal/large)
            hadleWidth: "20",
            // 当开关状态改变时触发
            onSwitchChange: function (event, state) {
                //修改操作
                $.ajax({
                    type: "post",
                    dataType: "json",
                    async: false,
                    url: jsctx + "/enterpriseMember/updateEnterpriseStatus",
                    data: {
                        status: state ? 0 : 1,
                        id: this.value
                    },
                    success: function (data) {
                        $('#TestTables').bootstrapTable('refresh'); //Table页面刷新
                    },
                    error: function (xhr, error, exception) {
                        let errorMsg = xhr.responseText;
                        parent.layer.alert("error", "系统异常，" + errorMsg + "，请联系管理员！");
                    }
                });
            }
        })
    }

    function addEnterpriseLevel() {
        location.href = prefix + "/addEnterpriseLevel";
    }

    function editEnterpriseLevel(id) {
        location.href = prefix + "/editEnterpriseLevel/" + id;
    }

    function deleteEnterpriseLevel(id) {
        layer.confirm('确定要删除该记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/deleteLevelSetting",
                type: "post",
                data: {
                    'enterpriseLevel': id
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    return {
        init: init,
        reLoad: reLoad,
        addEnterpriseLevel:addEnterpriseLevel,
        editEnterpriseLevel: editEnterpriseLevel,
        exportList: exportList,
        deleteEnterpriseLevel: deleteEnterpriseLevel

    };
})();

var addEnterpriseLevel = (function () {
    function init() {

        validateRule();
    };

    function save() {
        var formData = new FormData($("#frmEnterprise")[0]);
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/add",
            data: formData,
            processData: false,
            contentType: false,
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("成功");
                    javascript:history.back(-1);
                } else {
                    if (data.status == 600) {
                        javascript:history.back(-1);
                    } else {
                        parent.layer.alert(data.message);
                    }
                }
            }
        });
    };

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmEnterprise").validate({
            rules: {
                levelName: {
                    required: true
                },
                discountAmount: {
                    number: true,
                    min: 0,
                    max: 1
                }
            },
            messages: {
                levelName: {
                    required: icon + "请输入等级名称",
                },
                discountAmount: {
                    number: icon + "请输入有效数字",
                    min: icon + "请输入大于0的数字",
                    max: icon + "请输入小于1的数字",
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    };
    return {
        init: init
    };


})();

var editEnterpriseLevel = (function () {
    function init() {

        validateRule();
    };

    function save() {
        var formData = new FormData($("#frmEnterprise")[0]);
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/updateLevelSetting",
            data: formData,
            processData: false,
            contentType: false,
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("成功");
                    javascript:history.back(-1);
                } else {
                    if (data.status == 600) {
                        javascript:history.back(-1);
                    } else {
                        parent.layer.alert(data.message);
                    }
                }
            }
        });
    };

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmEnterprise").validate({
            rules: {
                levelName: {
                    required: true
                },
                discountAmount: {
                    number: true,
                    min: 0,
                    max: 1
                }
            },
            messages: {
                levelName: {
                    required: icon + "请输入等级名称",
                },
                discountAmount: {
                    number: icon + "请输入有效数字",
                    min: icon + "请输入大于0的数字",
                    max: icon + "请输入小于1的数字",
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    };
    return {
        init: init
    };


})();
